//
//  MessBtn.m
//  WGFGlobalHouses
//
//  Created by waiguofang on 15/7/10.
//  Copyright (c) 2015年 waiguofang. All rights reserved.
//

#import "MessBtn.h"
#import "IWBadgeButton.h"

@interface MessBtn()
@property (nonatomic,weak)IWBadgeButton *badgeButton;

@end

@implementation MessBtn
- (id)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        // 添加一个提醒数字按钮
        IWBadgeButton *badgeButton = [[IWBadgeButton alloc] init];
        badgeButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin;
        [self addSubview:badgeButton];
        self.badgeButton = badgeButton;
        
    }
    
    return self;
}


// 设置item
- (void)setBadge:(NSString *)badge
{
    _badge = badge;
    // KVO 监听属性改变
    [badge addObserver:self forKeyPath:@"badgeValue" options:0 context:nil];
    
    [self observeValueForKeyPath:@"badgeValue" ofObject:nil change:nil context:nil];
}


/**
 *  监听到某个对象的属性改变了,就会调用
 *
 *  @param keyPath 属性名
 *  @param object  哪个对象的属性被改变
 *  @param change  属性发生的改变
 */
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
       
    // 设置提醒数字
    self.badgeButton.badgeValue = _badge;
    
    if (self.badge) {
        self.hidden = NO;
        // 设置文字
        [self.badgeButton setTitle:self.badge forState:UIControlStateNormal];
        
        // 设置frame
        CGRect frame = self.badgeButton.frame;
        CGFloat badgeH =0;
        CGFloat badgeW =0;
        if (self.badge.length >=1) {
            // 文字的尺寸
            CGSize badgeSize = [self.badge sizeWithFont:self.titleLabel.font];
            badgeW = badgeSize.width;
        }
        frame.size.width = badgeW;
        frame.size.height = badgeH;
        self.badgeButton.frame = frame;
    } else {
        self.hidden = YES;
    }

    
    
    // 设置提醒数字的位置
    CGFloat badgeY = 5 + 5;
    CGFloat badgeX = self.frame.size.width - self.badgeButton.frame.size.width - 15;
    CGRect badgeF = self.badgeButton.frame;
    badgeF.origin.x = badgeX;
    badgeF.origin.y = badgeY;
    self.badgeButton.frame = badgeF;
}

@end
